package com.pactera.integral.service.impl;

import com.pactera.integral.common.repository.QueryResult;
import com.pactera.integral.common.repository.ResultMap;
import com.pactera.integral.dao.GroupDao;
import com.pactera.integral.dao.SummaryScoreDao;
import com.pactera.integral.dao.SummaryScoreHistoryDao;
import com.pactera.integral.dao.UserDao;
import com.pactera.integral.entity.SummaryScore;
import com.pactera.integral.entity.SummaryScoreHistory;
import com.pactera.integral.entity.User;
import com.pactera.integral.service.SummaryScoreService;
import com.pactera.integral.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SummaryScoreServiceImpl implements SummaryScoreService {

	private static Logger logger = LoggerFactory.getLogger(SummaryScoreServiceImpl.class);
	@Autowired
	private SummaryScoreDao scoreDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private GroupDao groupDao;

	@Autowired
	private SummaryScoreHistoryDao summaryScoreHistoryDao;

	/**
	 * 添加总分
	 */
	public String addScore(SummaryScore summaryScore) {
		logger.info("addScore");
		String message = "";
		// 状态'0'为新增， '1'为修改
		Integer status = 0;
		String staffId = summaryScore.getStaffId();
		Integer year = summaryScore.getYear();
		Integer month = summaryScore.getMonth();
		Integer additionalScore = summaryScore.getAdditionalScore();
		Integer performanceScore = summaryScore.getPerformanceScore();
		if (staffId == null || ("Id").equals(staffId)) {
			message = "idError";
			return message;
		}
		if (month == null || month <= 0 || month > 12) {
			message = "dateError";
			return message;
		}
		if (year == null || year <= 2000 || year > 2100) {
			message = "dateError";
			return message;
		}
		if (performanceScore < 0 || performanceScore > 100) {
			message = "scoreError";
			return message;
		}
		if (additionalScore < 0) {
			message = "scoreError";
			return message;
		}

		String userId = userDao.findByStaffId(staffId).getUserId();
		summaryScore.setUserId(userId);
		String scoreType = "TM";
		List<String> groupName = groupDao.findNamebyUserId(userId);
		if (groupName.contains("Team Leader")) {
			scoreType = "TL";
		}
		summaryScore.setScoreType(scoreType);

		SummaryScore existingScore = scoreDao.findByStaffIdAndYearAndMonth(staffId, year, month);
		if (existingScore != null) {
			existingScore.setStaffId(staffId);
			existingScore.setUserId(userId);
			existingScore.setMonth(month);
			existingScore.setScoreType(scoreType);
			existingScore.setYear(year);
			existingScore.setPerformanceScore(performanceScore);
			existingScore.setAdditionalScore(additionalScore);
			scoreDao.save(existingScore);
			message = "updateSuccess";
			status = 1;
		} else {
			scoreDao.save(summaryScore);
			message = "addSuccess";
		}
		addScoreHistory(staffId, userId, scoreType, month, year, performanceScore, additionalScore, status);
		return message;
	}

	/**
	 * 下拉框获取userId
	 * 
	 * @param staffId
	 * @return
	 */
	public List<ResultMap<String, Object>> getUserId(String staffId) {
		String sqlKey = "userId.searchByDepartmentCode";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		String departmentCode = getDepartmentCodebyStaffId(staffId, 1);
		parameterMap.put("departmentCode", departmentCode);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	/**
	 * 按部门，季度查询总分
	 */
	@Override
	public List<ResultMap<String, Object>> searchByDepartmentCode(String staffId, Integer scoreType) {
		String sqlKey = "summary.bySeason";
		Integer pageSize = 10;
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		String departmentCode = getDepartmentCodebyStaffId(staffId, scoreType);
        Calendar cal = Calendar.getInstance();
        Integer distYear = cal.get(Calendar.YEAR);
        if(scoreType == 0) {
			pageSize = 20;
			sqlKey = "summary.byYear";
        	distYear = distYear - 1;
        	departmentCode = departmentCode.substring(0,4);
		} else {
			parameterMap.put("scoreMonths", DateUtil.addMonths(scoreType));
        	if(scoreType == 1) {
				pageSize = 15;
				if(cal.get(Calendar.MONTH) < 3) distYear = distYear - 1;
			} else if(scoreType == 3) {
				sqlKey = "summary.byMonth";
			}
		}
		parameterMap.put("year", distYear);
		parameterMap.put("departmentCode", departmentCode);
		parameterMap.put("pageSize", pageSize);
		logger.info("SqlKey:{}, ParameterMap:{}", sqlKey, parameterMap);

		QueryResult<ResultMap<String, Object>> result = scoreDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	/**
	 * 查询历史记录
	 * 
	 * @param departmentCode
	 * @return
	 */
	public List<ResultMap<String, Object>> getScoreHistory(String departmentCode) {
		String sqlKey = "summaryScoreHistory.searchByDepartmentCode";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("departmentCode", departmentCode);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	/**
	 * 获取成员类别
	 */
	public List<ResultMap<String, Object>> getUserAuthority(String staffId) {
		String sqlKey = "userAuthority.searchByStaffId";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("staffId", staffId);
		QueryResult<ResultMap<String, Object>> result = userDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}

	/**
	 * 添加修改记录
	 * 
	 * @param staffId
	 * @param userId
	 * @param scoreType
	 * @param month
	 * @param year
	 * @param performanceScore
	 * @param additionalScore
	 * @param status
	 */
	private void addScoreHistory(String staffId, String userId, String scoreType, Integer month, Integer year,
			Integer performanceScore, Integer additionalScore, Integer status) {
		SummaryScoreHistory summaryScoreHistory = new SummaryScoreHistory();
		summaryScoreHistory.setStaffId(staffId);
		summaryScoreHistory.setUserId(userId);
		summaryScoreHistory.setScoreType(scoreType);
		summaryScoreHistory.setMonth(month);
		summaryScoreHistory.setYear(year);
		summaryScoreHistory.setPerformanceScore(performanceScore);
		summaryScoreHistory.setAdditionalScore(additionalScore);
		summaryScoreHistory.setStatus(status);
		summaryScoreHistoryDao.save(summaryScoreHistory);
	}

	private String getDepartmentCodebyStaffId(String staffId, Integer scoreType) {
		User uesr = userDao.findByStaffId(staffId);
		String departmentCode = "";
		if (scoreType != null && scoreType == 3) {
			departmentCode = uesr.getDepartmentCode();
		} else {
			departmentCode = uesr.getDepartmentCode().substring(0, 4);
		}
		return departmentCode;
	}

	/**
	 * 当月组内分数排行
	 */
	public List<ResultMap<String, Object>> searchMonthRankByDeparmentCode(String staffId, Integer scoreType) {
		String sqlKey = "monthRank.searchByDepartmentCode";
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		String departmentCode = getDepartmentCodebyStaffId(staffId, scoreType);
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		parameterMap.put("departmentCode", departmentCode);
		parameterMap.put("month", month);
		parameterMap.put("year", year);
		QueryResult<ResultMap<String, Object>> result = scoreDao.findMapListBySQLKey(sqlKey, parameterMap, null);

		return result.getContent();
	}
	
}
